import 'package:flutter/material.dart';
import 'package:media_kit/media_kit.dart';
import 'package:shared_preferences/shared_preferences.dart';

class VolumeMuteControllerWidget extends StatefulWidget {
  final Player player;

  const VolumeMuteControllerWidget({super.key, required this.player});

  @override
  State<VolumeMuteControllerWidget> createState() =>
      _VolumeMuteControllerWidgetState();
}

class _VolumeMuteControllerWidgetState
    extends State<VolumeMuteControllerWidget> {
  double volume = 0.0;
  double maxVolume = 100.0;

  final String playerVolumeKey = "playerVolume";

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((value) {
      volume = value.getDouble(playerVolumeKey) ?? widget.player.state.volume;
      // 如果默认就是静音，那么恢复后就是最大音量
      if (volume == 0) {
        volume = maxVolume;
      }
    });
  }

  void _onPressed() {
    if (widget.player.state.volume == 0) {
      widget.player.setVolume(volume);
      return;
    }
    volume = widget.player.state.volume;
    widget.player.setVolume(0);
    SharedPreferences.getInstance().then((value) {
      value.setDouble(playerVolumeKey, volume);
    });
  }

  @override
  Widget build(BuildContext context) {
    return IconButton(
      onPressed: _onPressed,
      icon: StreamBuilder(
        stream: widget.player.stream.volume,
        builder: (context, snapshot) => widget.player.state.volume == 0
            ? const Icon(Icons.volume_off)
            : const Icon(Icons.volume_up),
      ),
    );
  }
}
